//---------------------------------------------------------------------
//  This file is part of the Background Motion solution.
// 
//  Copyright (C) Mindscape (TM).  All rights reserved.
//  http://www.mindscape.co.nz
// 
//  THIS CODE AND INFORMATION ARE PROVIDED AS IS WITHOUT WARRANTY OF ANY
//  KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
//  IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
//  PARTICULAR PURPOSE.
//---------------------------------------------------------------------

using System;

using Microsoft.Practices.EnterpriseLibrary.Validation;

using Mindscape.BackgroundMotion.Core.Properties;

namespace Mindscape.BackgroundMotion.Core.Validators
{
  /// <summary>
  /// A validator that checks that a field contains a valid URL
  /// </summary>
  public class UrlValidatorAttribute : CustomValidatorAttribute
  {
    public UrlValidatorAttribute(string fieldName)
      : base(fieldName)
    {
    }

    /// <summary>
    /// Does the create validator.
    /// </summary>
    /// <param name="targetType">Type of the target.</param>
    /// <returns></returns>
    protected override Validator DoCreateValidator(Type targetType)
    {
      return new UrlValidator(FieldName);
    }
  }

  /// <summary>
  /// A validator that checks that a field contains a valid URL
  /// </summary>
  public class UrlValidator : CustomValidator<string>
  {
    public UrlValidator(string fieldName)
      : base(fieldName)
    {
    }

    /// <summary>
    /// Performs the validation
    /// </summary>
    /// <param name="objectToValidate">The object to validate.</param>
    /// <param name="currentTarget">The current target.</param>
    /// <param name="key">The key.</param>
    /// <param name="validationResults">The validation results.</param>
    protected override void DoValidate(string objectToValidate, object currentTarget, string key, ValidationResults validationResults)
    {
      Uri uri;

      if (!Uri.TryCreate(objectToValidate, UriKind.Absolute, out uri))
      {
        LogValidationResult(validationResults, MessageTemplate, currentTarget, key);
      }
    }

    /// <summary>
    /// Gets the message resource.
    /// </summary>
    /// <value>The message resource.</value>
    protected override string MessageResource
    {
      get { return Resources.UrlNotValid; }
    }
  }
}